package cn.otrue.patienthealthmanager.fragment;

import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.activity.CenterAboutActivity;
import cn.otrue.patienthealthmanager.activity.CenterFeedbackActivity;
import cn.otrue.patienthealthmanager.activity.CenterHelpActivity;
import cn.otrue.patienthealthmanager.activity.CenterInfoActivity;
import cn.otrue.patienthealthmanager.activity.CenterMessageActivity;
import cn.otrue.patienthealthmanager.activity.CenterScoreActivity;
import cn.otrue.patienthealthmanager.activity.CenterSettingsActivity;
import cn.otrue.patienthealthmanager.activity.CenterjifenActivity;
import cn.otrue.patienthealthmanager.activity.FuJinActivity;
import cn.otrue.patienthealthmanager.activity.LoginActivity;
import cn.otrue.patienthealthmanager.activity.PasswordChangeActivity;
import cn.otrue.patienthealthmanager.activity.QuestionnaireList;
import cn.otrue.patienthealthmanager.activity.RegisterActivity;
import cn.otrue.patienthealthmanager.activity.ShebeiActivity;
import cn.otrue.patienthealthmanager.activity.WodeActivity;
import cn.otrue.patienthealthmanager.bean.PatientModel;
import cn.otrue.patienthealthmanager.bean.TransferParameter;
import cn.otrue.patienthealthmanager.http.HttpCons;
import cn.otrue.patienthealthmanager.http.HttpServer;
import cn.otrue.patienthealthmanager.http.ServerHandler;
import cn.otrue.patienthealthmanager.socialshare.SocialShare;
import cn.otrue.patienthealthmanager.utils.CommonUtil;
import cn.otrue.patienthealthmanager.utils.DensityUtil;
import cn.otrue.patienthealthmanager.utils.DialogUtil;
import cn.otrue.patienthealthmanager.utils.MyConst;
import cn.otrue.patienthealthmanager.xmpp.XmppTool;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

/**
 * 个人中心
 * 
 * @author G
 * 
 */
public class PersonalCenterFragment extends BaseFragment {

	private View rootView;

	private Button btn_fragment_center_login, btn_fragment_center_register;

	private RelativeLayout rl_fragment_center_help, center_feed_back, rl_about;
	private Button btn_exit_login, btn_doctor_change_password;
	private String mymind;
	private String autoAuth;
	private TextView btn_my_set;

	private TextView btn_center_message;

	private TextView btn_my_tiezi;

	private TextView btn_person_info;

	private TextView bt_waishe;
	private PatientModel tuuu;
	private TextView btn_my_score;
	private AlertDialog alertDialog;

	private HorizontalScrollView hs_ll;

	private ImageView pe_head_image;

	private TextView huanying;
	private SocialShare socialShare; // 变量
	private LinearLayout ll_center_no_login;
	private LinearLayout ll_center_yes_login;
	public static Activity activity;
	private TextView tv_patient_wenjuan;

	public void ImageSet(String imgurl, ImageView img_headPhoto) {

		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.iv_user_photo)
				.showImageOnFail(R.drawable.iv_user_photo)
				.cacheInMemory(true)
				.cacheOnDisk(true)
				.bitmapConfig(Bitmap.Config.RGB_565)
				.displayer(
						new RoundedBitmapDisplayer(DensityUtil.dip2px(
								rootView.getContext(), 40))).build();
		ImageLoader.getInstance().displayImage(imgurl, img_headPhoto, options);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_center, container, false);
		MyConst.PATIENT = null;
		initView(rootView);
		activity = getActivity();
		return rootView;
	}

	int i = 0;

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (isVisibleToUser) {
			if (!(MyConst.getACCOUNT().isEmpty())) {
				if (MyConst.PATIENT != null) {
					i = 1;
					tuuu = MyConst.PATIENT;
					autoAuth = tuuu.getAutoAuth();
					mymind = tuuu.getMyMind();
					huanying.setText("欢迎："
							+ CommonUtil.getName(tuuu.nickName, tuuu
									.getRealname(), MyConst.getACCOUNT()
									.substring(1)));
					if (tuuu.getHeadimg() != null) {
						String img = tuuu.getHeadimg().toString();
						MyConst.HEADIMG = img;
						ImageSet(img, pe_head_image);
					}
				} else {
					inti();
				}

			}
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		if (!(MyConst.getACCOUNT().isEmpty())) {
			if (MyConst.PATIENT != null) {
				i = 1;
				tuuu = MyConst.PATIENT;
				autoAuth = tuuu.getAutoAuth();
				mymind = tuuu.getMyMind();
				huanying.setText("欢迎："+ CommonUtil.getName(tuuu.nickName, tuuu.getRealname(),MyConst.getACCOUNT().substring(1)));
				if (tuuu.getHeadimg() != null) {
					String img = tuuu.getHeadimg().toString();
					MyConst.HEADIMG = img;
					ImageSet(img, pe_head_image);
				}
			} else {
				inti();
			}
		}
		if (MyConst.getACCOUNT().equals("")) {
			huanying.setVisibility(View.GONE);
			pe_head_image.setVisibility(View.GONE);
			ll_doubi.setVisibility(View.GONE);
			btn_exit_login.setVisibility(View.GONE);
			ll_center_yes_login.setVisibility(View.GONE);
			ll_center_no_login.setVisibility(View.VISIBLE);
			btn_doctor_change_password.setVisibility(View.GONE);
		} else {
			ll_center_no_login.setVisibility(View.GONE);
			ll_center_yes_login.setVisibility(View.VISIBLE);
			btn_exit_login.setVisibility(View.VISIBLE);
			btn_doctor_change_password.setVisibility(View.VISIBLE);
			pe_head_image.setVisibility(View.VISIBLE);
			ll_doubi.setVisibility(View.VISIBLE);
			huanying.setVisibility(View.VISIBLE);
		}
		if (MyConst.PATIENT != null) {
			if ((MyConst.PATIENT.headimg != null)
					&& !("".equals(MyConst.PATIENT.headimg))) {
				if (!MyConst.getACCOUNT().equals("")) {
					huanying.setVisibility(View.VISIBLE);
				} else {

					huanying.setVisibility(View.GONE);
				}
				if ((MyConst.PATIENT.headimg != null)
						&& !("".equals(MyConst.PATIENT.headimg))) {
					ImageSet(MyConst.PATIENT.headimg, pe_head_image);
				}
				huanying.setText("欢迎："+ CommonUtil.getName(MyConst.PATIENT.nickName,MyConst.PATIENT.realname,MyConst.PATIENT.aliasAccount) + "   登陆");
			}
		}
	}

	private void initView(View rootView) {
		socialShare = new SocialShare(); // 初始化
		tv_banben = (TextView) rootView.findViewById(R.id.tv_banben);
		PackageManager manger = getActivity().getPackageManager();
		try {
			PackageInfo info = manger.getPackageInfo(getActivity()
					.getPackageName(), 0);
			tv_banben.setText("版本" + info.versionName);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}

		rl_fragment_center_h = (RelativeLayout) rootView
				.findViewById(R.id.rl_fragment_center_h);
		rl_fragment_center_h.setOnClickListener(this);
		socialShare.setContext(PersonalCenterFragment.this.getActivity());
		pe_head_image = (ImageView) rootView.findViewById(R.id.pe_head_image);
		ll_doubi = (RelativeLayout) rootView.findViewById(R.id.ll_doubi);
		ll_center_no_login = (LinearLayout) rootView
				.findViewById(R.id.ll_center_no_login);
		ll_center_yes_login = (LinearLayout) rootView
				.findViewById(R.id.ll_center_yes_login);
		huanying = (TextView) rootView.findViewById(R.id.huanying);
		// btn_zhuce = (Button) rootView.findViewById(R.id.btn_zhuce);
		// btn_zhuce.setOnClickListener(this);
		bt_waishe = (TextView) rootView.findViewById(R.id.bt_waishe);
		bt_waishe.setOnClickListener(this);
		hs_ll = (HorizontalScrollView) rootView.findViewById(R.id.hs_ll);
		hs_ll.setOnClickListener(this);
		btn_fragment_center_login = (Button) rootView
				.findViewById(R.id.btn_fragment_center_login);
		btn_fragment_center_login.setOnClickListener(this);
		btn_fragment_center_register = (Button) rootView
				.findViewById(R.id.btn_fragment_center_register);
		btn_fragment_center_register.setOnClickListener(this);
		btn_person_info = (TextView) rootView
				.findViewById(R.id.btn_person_info);
		btn_person_info.setOnClickListener(this);
		btn_my_tiezi = (TextView) rootView.findViewById(R.id.btn_my_tiezi);
		btn_my_tiezi.setOnClickListener(this);
		btn_center_message = (TextView) rootView
				.findViewById(R.id.btn_center_message);
		btn_center_message.setOnClickListener(this);
		btn_my_set = (TextView) rootView.findViewById(R.id.btn_my_set);
		btn_my_set.setOnClickListener(this);
		rl_fragment_center_help = (RelativeLayout) rootView
				.findViewById(R.id.rl_fragment_center_help);
		rl_fragment_center_help.setOnClickListener(this);
		center_feed_back = (RelativeLayout) rootView
				.findViewById(R.id.center_feed_back);
		center_feed_back.setOnClickListener(this);
		rl_about = (RelativeLayout) rootView.findViewById(R.id.rl_about);
		rl_about.setOnClickListener(this);
		rl_fujin = (RelativeLayout) rootView.findViewById(R.id.rl_fujin);
		rl_fujin.setOnClickListener(this);
		rl_fenheng = (RelativeLayout) rootView.findViewById(R.id.rl_fenheng);
		rl_fenheng.setOnClickListener(this);

		btn_exit_login = (Button) rootView.findViewById(R.id.btn_exit_login);
		btn_exit_login.setOnClickListener(this);
		// btn_login = (Button) rootView.findViewById(R.id.btn_login);
		// btn_login.setOnClickListener(this);

		btn_doctor_change_password = (Button) rootView
				.findViewById(R.id.btn_doctor_change_password);
		btn_doctor_change_password.setOnClickListener(this);
		btn_my_score = (TextView) rootView.findViewById(R.id.btn_my_score);
		tv_patient_wenjuan = (TextView) rootView
				.findViewById(R.id.tv_patient_wenjuan);
		tv_patient_wenjuan.setOnClickListener(this);
		if (!MyConst.getACCOUNT().equals("")) {
			btn_exit_login.setVisibility(View.VISIBLE);
			btn_doctor_change_password.setVisibility(View.VISIBLE);
		} else {
			btn_doctor_change_password.setVisibility(View.GONE);
			btn_exit_login.setVisibility(View.GONE);
		}

	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.btn_fragment_center_login:
			Intent loginIntent = new Intent(getActivity(), LoginActivity.class);
			startActivity(loginIntent);
			// getActivity().finish();
			break;
		case R.id.btn_fragment_center_register:
			Intent registerIntent = new Intent(getActivity(),
					RegisterActivity.class);
			startActivity(registerIntent);
			break;
		case R.id.rl_fragment_center_h:
			Intent intyy = new Intent(getActivity(), CenterjifenActivity.class);
			startActivity(intyy);
			break;

		case R.id.btn_person_info:
			if (MyConst.getACCOUNT().equals("")) {
				View dialogView = initDataInputDialog(new DataDialogListener(),
						0);
				if (null != dialogView)
					alertDialog = DialogUtil.showDialog(
							PersonalCenterFragment.this.getActivity(),
							dialogView, true);
			} else {
				Intent personinfoIntent = new Intent(getActivity(),
						CenterInfoActivity.class);
				startActivity(personinfoIntent);

			}
			break;
		case R.id.btn_my_tiezi:
			if (MyConst.getACCOUNT().equals("")) {
				View dialogView = initDataInputDialog(new DataDialogListener(),
						0);
				if (null != dialogView)
					alertDialog = DialogUtil.showDialog(
							PersonalCenterFragment.this.getActivity(),
							dialogView, true);
			} else {
				Intent Intent = new Intent(getActivity(), WodeActivity.class);
				startActivity(Intent);

			}

			break;
		case R.id.btn_center_message:
			if (MyConst.getACCOUNT().equals("")) {
				View dialogView = initDataInputDialog(new DataDialogListener(),
						0);
				if (null != dialogView)
					alertDialog = DialogUtil.showDialog(
							PersonalCenterFragment.this.getActivity(),
							dialogView, true);
			} else {
				Intent centermessageIntent = new Intent(getActivity(),
						CenterMessageActivity.class);
				startActivity(centermessageIntent);

			}

			break;
		case R.id.btn_my_set:
			if (MyConst.getACCOUNT().equals("")) {
				View dialogView = initDataInputDialog(new DataDialogListener(),
						0);
				if (null != dialogView)
					alertDialog = DialogUtil.showDialog(
							PersonalCenterFragment.this.getActivity(),
							dialogView, true);
			} else {
				Intent centerSetIntent = new Intent(getActivity(),
						CenterSettingsActivity.class);
				centerSetIntent.putExtra("myMind", mymind);
				centerSetIntent.putExtra("autoAuth", autoAuth);

				startActivity(centerSetIntent);

			}

			break;
		case R.id.rl_fragment_center_help:
			Intent helpCenterIntent = new Intent(getActivity(),
					CenterHelpActivity.class);
			startActivity(helpCenterIntent);
			break;
		case R.id.center_feed_back:
			if (MyConst.getACCOUNT().equals("")) {
				View dialogView = initDataInputDialog(new DataDialogListener(),
						0);
				if (null != dialogView)
					alertDialog = DialogUtil.showDialog(
							PersonalCenterFragment.this.getActivity(),
							dialogView, true);
			} else {
				Intent feedbackIntent = new Intent(getActivity(),
						CenterFeedbackActivity.class);
				startActivity(feedbackIntent);

			}

			break;
		case R.id.rl_about:
			Intent aboutIntent = new Intent(getActivity(),
					CenterAboutActivity.class);
			startActivity(aboutIntent);
			break;
		case R.id.rl_fujin:
			Intent aboutInte = new Intent(getActivity(), FuJinActivity.class);
			startActivity(aboutInte);
			break;

		case R.id.btn_exit_login:
			MyConst.setACCOUNT("");
			MyConst.TOKEN = "";
			btn_exit_login.setVisibility(View.GONE);
			btn_doctor_change_password.setVisibility(View.GONE);
			ll_center_no_login.setVisibility(View.VISIBLE);
			huanying.setVisibility(View.GONE);
			pe_head_image.setVisibility(View.GONE);
			ll_doubi.setVisibility(View.GONE);
			XmppTool.closeConnection();

			TransferParameter parameter = new TransferParameter();
			HashMap<String, Object> data = new HashMap<String, Object>();
			parameter.setData(data);
			new HttpServer().post(HttpCons.ONLINE_USER_DOWN, parameter,
					offLineHandler);
			break;
		case R.id.btn_doctor_change_password:

			Intent changePwdIntent = new Intent(getActivity(),
					PasswordChangeActivity.class);
			startActivity(changePwdIntent);
			break;
		case R.id.btn_my_score:
			Intent myScoreIntent = new Intent(getActivity(),
					CenterScoreActivity.class);
			startActivity(myScoreIntent);
			break;
		// case R.id.btn_login:
		//
		// Intent mIntent = new Intent(getActivity(), LoginActivity.class);
		// startActivity(mIntent);
		// getActivity().finish();
		// break;
		case R.id.rl_fenheng:
			if (MyConst.getACCOUNT().equals("")) {
				View dialogView = initDataInputDialog(new DataDialogListener(),
						0);
				if (null != dialogView)
					alertDialog = DialogUtil.showDialog(
							PersonalCenterFragment.this.getActivity(),
							dialogView, true);
			} else {
				socialShare.socialShare();

			}

			break;
		case R.id.tv_patient_wenjuan:
			if (MyConst.getACCOUNT().equals("")) {
				View dialogView = initDataInputDialog(new DataDialogListener(),
						0);
				if (null != dialogView)
					alertDialog = DialogUtil.showDialog(
							PersonalCenterFragment.this.getActivity(),
							dialogView, true);
			} else {
				Intent surveyIntent = new Intent(getActivity(),
						QuestionnaireList.class);
				startActivity(surveyIntent);
			}
			break;
		case R.id.bt_waishe:
			if (MyConst.getACCOUNT().equals("")) {
				View dialogView = initDataInputDialog(new DataDialogListener(),
						0);
				if (null != dialogView)
					alertDialog = DialogUtil.showDialog(
							PersonalCenterFragment.this.getActivity(),
							dialogView, true);
				break;
			} else {
				Intent mInte = new Intent(getActivity(), ShebeiActivity.class);
				startActivity(mInte);
				break;
			}
		}
	}

	private Handler offLineHandler = new ServerHandler() {
		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			if (state.equals("001")) {
				Log.e("user", "下线成功");
			} else {
				Log.e("user", "下线失败");
			}
		}

		@Override
		public void onFail(Bundle data, String state) {
		}
	};

	private Handler Handler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			String tuu = data.getString(HttpCons.DATA);
			if (state.equals("001")) {

				i = 1;
				Gson gson = HttpServer.gson;

				tuuu = gson.fromJson(tuu, PatientModel.class);
				MyConst.PATIENT = tuuu;
				autoAuth = tuuu.getAutoAuth();
				mymind = tuuu.getMyMind();
				huanying.setText("欢迎："
						+ CommonUtil.getName(tuuu.nickName, tuuu.getRealname(),
								MyConst.getACCOUNT().substring(1)));
				if (tuuu.getHeadimg() != null) {
					String img = tuuu.getHeadimg().toString();
					MyConst.HEADIMG = img;
					ImageSet(img, pe_head_image);
				}
				Toast.makeText(rootView.getContext(), "操作成功", 0).show();
			} else {
				// Toast.makeText(rootView.getContext(), msg, 0).show();
			}
		}

		@Override
		public void onFail(Bundle data, String state) {

			if (state.equals(HttpCons.STATE_EXCEPTION)) {
				// 代表进入状态STATE_EXCEPTION 网络异常
				Toast.makeText(rootView.getContext(), "网络异常,请稍后重试",
						Toast.LENGTH_SHORT).show();

			} else if (state.equals(HttpCons.STATE_FORMAT_ERROR)) {
				// 代表进入STATE_FORMAT_ERROR(不是Json)
			} else {
				// 代表进入STATE_ANALYTICAL_ERROR(Json解析错误)

			}
		}
	};

	private RelativeLayout rl_fenheng;

	private RelativeLayout rl_fujin;

	private TextView tv_banben;

	private RelativeLayout ll_doubi;

	private RelativeLayout rl_fragment_center_h;

	private void inti() {
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("aliasAccount", MyConst.getACCOUNT());
		TransferParameter parameter = new TransferParameter();
		parameter.setUsername("");
		parameter.setPassword("");
		parameter.setCurrentPage("");
		parameter.setPagesize("");
		parameter.setData(map);

		new HttpServer()
				.post(HttpCons.queryPatientBaseinfo, parameter, Handler);

	}

	private View initDataInputDialog(DataDialogListener dataListener, int i) {
		LayoutInflater inflater = LayoutInflater.from(rootView.getContext());
		View view = inflater.inflate(R.layout.dialog_input_daaa, null);
		TextView tv_catt_dialogLeft = (TextView) view
				.findViewById(R.id.tv_catt_dialogLeft);
		tv_catt_dialogLeft.setOnClickListener(dataListener);
		TextView tv_catt_dialogRight = (TextView) view
				.findViewById(R.id.tv_catt_dialogRight);
		tv_catt_dialogRight.setOnClickListener(dataListener);
		return view;

	}

	public class DataDialogListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.tv_catt_dialogLeft:// 取消
				alertDialog.dismiss();
				break;
			case R.id.tv_catt_dialogRight:// 确定

				Intent personinfoIntent = new Intent(getActivity(),
						LoginActivity.class);
				startActivity(personinfoIntent);
				alertDialog.dismiss();

			}
		}

	}

	@Override
	public String setPageName() {
		// TODO Auto-generated method stub
		return null;
	}

	public static Fragment newInstance() {
		// TODO Auto-generated method stub
		return new PersonalCenterFragment();
	}

}